import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/mixin/auto_hide_loading.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/utils/a_logger.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class VerificationCodePage extends StatefulWidget {
  final Map<String, dynamic>? args;

  const VerificationCodePage(this.args, {super.key});

  @override
  State<StatefulWidget> createState() {
    return VerificationCodeState(this.args);
  }
}

class VerificationCodeState extends State<VerificationCodePage>
    with AutoHideLoading {
  final Map<String, dynamic>? args;
  final TextEditingController _textController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  VerificationCodeState(this.args);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:
          commonAppBar(AppLocalizations.of(context)!.enterTheVerificationCode),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: ChangeNotifierProvider(
          create: (ctx) => VerificationCodeVideModel(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 82),
                child: Stack(children: [
                  GridView.builder(
                    shrinkWrap: true,
                    gridDelegate:
                    const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 6,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 0,
                      childAspectRatio: 0.75,
                    ),
                    itemCount: 6,
                    itemBuilder: (context, index) {
                      return Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: const Color(0xffEAECEE),
                        ),
                        child: Center(
                          child: Text(
                            Provider.of<VerificationCodeVideModel>(context)
                                .getNum(index) ??
                                "",
                            style: const TextStyle(
                                color: Colors.black, fontSize: 22),
                          ),
                        ),
                      );
                    },
                  ),
                  Opacity(
                    opacity: 0,
                    child: Builder(builder: (context) {
                      return TextField(
                        autofocus: true,
                        textAlign: TextAlign.center,
                        keyboardType: TextInputType.number,
                        maxLength: 6,
                        cursorColor: Colors.black,
                        style:
                        TextStyle(fontWeight: FontWeight.normal, fontSize: 20),
                        decoration: const InputDecoration(
                          border: OutlineInputBorder(borderSide: BorderSide.none),
                          counterText: '',
                          fillColor: Color(0xffEAECEE),
                          filled: true,
                          hintStyle: TextStyle(color: Colors.black, fontSize: 20.0),
                        ),
                        controller: _textController,
                        onChanged: (value) {
                          VerificationCodeVideModel vm =
                          context.read<VerificationCodeVideModel>();
                          vm.updateNum(value);
                          if (value.length >= 6) {
                            vm.register(context, args?['email'], args?['password'],
                                _textController.text, args?['change'] != null);
                          }
                        },
                      );
                    }),
                  ),
                ],),
              ),
              const SizedBox(height: 5),
              Consumer<VerificationCodeVideModel>(
                builder: (context, value, child) {
                  return Opacity(
                    opacity:
                        context.watch<VerificationCodeVideModel>().errMsg !=
                                null
                            ? 1
                            : 0,
                    child: Text(
                      "*${value.errMsg}",
                      style: const TextStyle(
                          color: Color(0xffFF4747), fontSize: 11),
                    ),
                  );
                },
              ),
              Builder(builder: (context) {
                return CupertinoButton(
                  padding: EdgeInsets.zero,
                  onPressed: () {
                    context.read<VerificationCodeVideModel>().register(
                        context,
                        widget.args?['email'],
                        args?['password'],
                        _textController.text,
                        args?['change'] != null);
                  },
                  child: Container(
                    margin: const EdgeInsets.only(top: 79.5),
                    height: 57,
                    decoration: BoxDecoration(
                        color: const Color(0xff3F74EF),
                        borderRadius: BorderRadius.circular(28.5)),
                    child: Center(
                      child: Text(
                        AppLocalizations.of(context)!.next,
                        style: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                );
              }),
              SizedBox(
                height: 15,
              ),
              Text(
                AppLocalizations.of(context)!.sendCodeSuccessTip,
                style: const TextStyle(color: Color(0xff999999), fontSize: 11),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }
}

class VerificationCodeVideModel extends ChangeNotifier {
  String? errMsg;

  String _num = "";

  void updateNum(String num) {
    _num = num;
    notifyListeners();
  }

  String? getNum(int idx) {
    if (idx >= 0 && idx < _num.length) {
      return _num[idx];
    }
    return null;
  }

  Future<dynamic> register(BuildContext context, String email, String? password,
      String code, bool change) async {
    if (code.isEmpty || code.length < 6) {
      errMsg = AppLocalizations.of(context)!.verificationCodeIncorrect;
      notifyListeners();
      return Future.value(null);
    }
    await EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    );
    return HttpManager.instance.doRequest("/verify",
        parameters: {"email": email, "code": code}).then((e) {
      if (e.isSuccess) {
        return true;
      }
      Fluttertoast.showToast(msg: e.msg ?? "");
      return false;
    }).catchError((e) {
      Fluttertoast.showToast(msg: AppLocalizations.of(context)!.netError);
      return false;
    }).then((e) async {
      if (e == true) {
        if (change) {
          ARouter.instance
              .pagePush('/changePassword', arguments: {"email": email});
          return true;
        }
        final registerRes = await HttpManager.instance.doRequest(
            "/user/register",
            parameters: {"email": email, "pwd": password});
        if (registerRes.isSuccess) {
          Fluttertoast.showToast(
              msg: AppLocalizations.of(context)!.registerSuccessful);
          await UserManager.instance.logout();
          return true;
        }
        Fluttertoast.showToast(msg: registerRes.msg ?? "");
        return false;
      }
      return false;
    }).whenComplete(() {
      EasyLoading.dismiss();
    });
  }
}
